package com.xdcplus.web.service.pm.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.xdcplus.core.utils.BeanUtils;
import com.xdcplus.exceptions.XdcWebException;
import com.xdcplus.mom.constants.NumberConstant;
import com.xdcplus.mom.enums.ResponseEnum;
import com.xdcplus.mp.service.impl.BaseServiceImpl;
import com.xdcplus.mp.utils.PageableUtils;
import com.xdcplus.mp.utils.PropertyUtils;
import com.xdcplus.pager.vo.PageVO;
import com.xdcplus.web.common.pojo.dto.pm.PmShiftPlanGroupBindDTO;
import com.xdcplus.web.common.pojo.dto.pm.PmShiftPlanGroupDTO;
import com.xdcplus.web.common.pojo.dto.pm.PmShiftPlanGroupFilterDTO;
import com.xdcplus.web.common.pojo.entity.pm.PmShiftPlanGroup;
import com.xdcplus.web.common.pojo.query.pm.PmShiftPlanGroupQuery;
import com.xdcplus.web.common.pojo.vo.pm.PmShiftPlanGroupVO;
import com.xdcplus.web.mapper.pm.PmShiftPlanGroupMapper;
import com.xdcplus.web.service.bd.BdClassGroupService;
import com.xdcplus.web.service.pm.PmShiftPlanGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 排班计划班组(PmShiftPlanGroup)表服务实现类
 *
 * @author Fish.Fei
 * @since 2023-05-05 15:22:36
 */
@Slf4j
@Service("pmShiftPlanGroupService")
public class PmShiftPlanGroupServiceImpl extends BaseServiceImpl<PmShiftPlanGroupMapper, PmShiftPlanGroup, PmShiftPlanGroup, PmShiftPlanGroupVO> implements PmShiftPlanGroupService {

    @Autowired
    protected PmShiftPlanGroupMapper pmShiftPlanGroupMapper;

    @Autowired
    protected BdClassGroupService bdClassGroupService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean savePmShiftPlanGroup(PmShiftPlanGroupDTO pmShiftPlanGroupDTO) {

        PmShiftPlanGroup pmShiftPlanGroup = new PmShiftPlanGroup();
        BeanUtil.copyProperties(pmShiftPlanGroupDTO, pmShiftPlanGroup);
        pmShiftPlanGroup.setCreatedTime(new Timestamp(DateUtil.current()));
        
        return this.save(pmShiftPlanGroup);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean updatePmShiftPlanGroup(PmShiftPlanGroupDTO pmShiftPlanGroupDTO) {

        PmShiftPlanGroup pmShiftPlanGroup = this.getById(pmShiftPlanGroupDTO.getId());
        if (ObjectUtil.isNull(pmShiftPlanGroup)) {
            log.error("updatePmShiftPlanGroup() The PmShiftPlanGroup does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }

        BeanUtil.copyProperties(pmShiftPlanGroupDTO, pmShiftPlanGroup);
        pmShiftPlanGroup.setUpdatedUser(pmShiftPlanGroupDTO.getUpdatedUser());
        pmShiftPlanGroup.setUpdatedTime(new Timestamp(DateUtil.current()));

        return this.updateById(pmShiftPlanGroup);
    }

    @Override
    public Boolean saveOrUpdateBatch(List<PmShiftPlanGroup> pmShiftPlanGroupList) {

        pmShiftPlanGroupList.forEach(pmShiftPlanGroup -> {
            PmShiftPlanGroup pmShiftPlanGroupParam = new PmShiftPlanGroup();
            pmShiftPlanGroupParam.setId(pmShiftPlanGroup.getId());
            if (ObjectUtil.isNotNull(pmShiftPlanGroup.getId())) {
                pmShiftPlanGroup.setId(pmShiftPlanGroup.getId());
                pmShiftPlanGroup.setUpdatedTime(new Timestamp(DateUtil.current()));
                LambdaUpdateWrapper<PmShiftPlanGroup> lambdaUpdate = Wrappers.lambdaUpdate();
                lambdaUpdate.eq(PmShiftPlanGroup::getId, pmShiftPlanGroup.getId());
                update(pmShiftPlanGroup, lambdaUpdate);
            } else {
                pmShiftPlanGroup.setCreatedTime(new Timestamp(DateUtil.current()));
                save(pmShiftPlanGroup);
            }
        });
        return true;
    }

    @Override
    public Boolean saveOrUpdateBatchByDTOList(List<PmShiftPlanGroupDTO> pmShiftPlanGroupDTOList) {

        List<PmShiftPlanGroup> pmShiftPlanGroupList = BeanUtils.copyProperties(pmShiftPlanGroupDTOList, PmShiftPlanGroup.class);
        return saveOrUpdateBatch(pmShiftPlanGroupList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deletePmShiftPlanGroupLogical(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        PmShiftPlanGroup pmShiftPlanGroup = this.getById(id);

        if (ObjectUtil.isNull(pmShiftPlanGroup)) {
            log.error("deletePmShiftPlanGroup() The PmShiftPlanGroup does not exist or has been deleted");
            throw new XdcWebException(ResponseEnum.ERROR);
        }
        return this.removeById(id);
    }
    
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean deletePmShiftPlanGroupByIds(String ids) {
        Assert.notNull(ids, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());
		List<String> idList = Arrays.asList(ids.split(","));
		if(CollectionUtil.isEmpty(idList)){
           throw new XdcWebException(ResponseEnum.ERROR);
       }
		idList.forEach(id->{
			PmShiftPlanGroup pmShiftPlanGroup = this.getById(id);
			if (ObjectUtil.isNull(pmShiftPlanGroup)) {
				log.error("deletePmShiftPlanGroup() The PmShiftPlanGroup does not exist or has been deleted");
				throw new XdcWebException(ResponseEnum.ERROR);
			}
		});
		
        return this.removeByIds(idList);
    }

    private List<PmShiftPlanGroup> queryPmShiftPlanGroupList(PmShiftPlanGroupFilterDTO pmShiftPlanGroupFilterDTO) {
        PmShiftPlanGroupQuery pmShiftPlanGroupQuery = BeanUtil.copyProperties(pmShiftPlanGroupFilterDTO, PmShiftPlanGroupQuery.class);

        return pmShiftPlanGroupMapper.queryPmShiftPlanGroup(pmShiftPlanGroupQuery);
    }

    @Override
    public List<PmShiftPlanGroupVO> queryPmShiftPlanGroupVOList(PmShiftPlanGroupFilterDTO pmShiftPlanGroupFilterDTO) {
        return this.objectConversion(queryPmShiftPlanGroupList(pmShiftPlanGroupFilterDTO));
    }

    @Override
    public PageVO<PmShiftPlanGroupVO> queryPmShiftPlanGroup(PmShiftPlanGroupFilterDTO pmShiftPlanGroupFilterDTO) {
        PageVO<PmShiftPlanGroupVO> pageVO = new PageVO<>();

        if (pmShiftPlanGroupFilterDTO.getCurrentPage() > NumberConstant.ZERO) {
            PageableUtils.basicPage(pmShiftPlanGroupFilterDTO.getCurrentPage(), pmShiftPlanGroupFilterDTO.getPageSize(),
                    pmShiftPlanGroupFilterDTO.getOrderType(), pmShiftPlanGroupFilterDTO.getOrderField());
        }

        List<PmShiftPlanGroup> pmShiftPlanGroupList = queryPmShiftPlanGroupList(pmShiftPlanGroupFilterDTO);

        PageInfo<PmShiftPlanGroup> pageInfo = new PageInfo<>(pmShiftPlanGroupList);
        PropertyUtils.copyProperties(pageInfo, pageVO, this.objectConversion(pmShiftPlanGroupList));

        return pageVO;
    }

    @Override
    public PmShiftPlanGroupVO queryPmShiftPlanGroupById(Long id) {

        Assert.notNull(id, ResponseEnum.THE_ID_CANNOT_BE_EMPTY.getMessage());

        return this.objectConversion(this.getById(id));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void batchBindPmShiftPlanGroup(PmShiftPlanGroupBindDTO pmShiftPlanGroupBindDTO) {
        judgeRationality(pmShiftPlanGroupBindDTO);

        pmShiftPlanGroupMapper.delete(new QueryWrapper<PmShiftPlanGroup>()
                        .eq("SHIFT_PLAN_ID_FK", pmShiftPlanGroupBindDTO.getShiftPlanIdFk())
                .eq("SHIFT_MANAGE_ID_FK", pmShiftPlanGroupBindDTO.getShiftManageIdFk()));

        if(CollectionUtil.isNotEmpty(pmShiftPlanGroupBindDTO.getClassGroupIdFks())){
            PmShiftPlanGroupDTO pmShiftPlanGroupDTO;
            for (Long classGroupIdFk : pmShiftPlanGroupBindDTO.getClassGroupIdFks()) {
                pmShiftPlanGroupDTO = new PmShiftPlanGroupDTO();
                pmShiftPlanGroupDTO.setShiftPlanIdFk(pmShiftPlanGroupBindDTO.getShiftPlanIdFk());
                pmShiftPlanGroupDTO.setShiftManageIdFk(pmShiftPlanGroupBindDTO.getShiftManageIdFk());
                pmShiftPlanGroupDTO.setClassGroupIdFk(classGroupIdFk);
                savePmShiftPlanGroup(pmShiftPlanGroupDTO);
            }
        }
    }

    @Override
    public void deletePmShiftPlanGroupByPlanId(Long shiftPlanIdFk) {
        pmShiftPlanGroupMapper.delete(new QueryWrapper<PmShiftPlanGroup>().eq("SHIFT_PLAN_ID_FK",shiftPlanIdFk));
    }


    @Override
    public PmShiftPlanGroupVO objectConversion(PmShiftPlanGroup s) {
        PmShiftPlanGroupVO pmShiftPlanGroupVO = super.objectConversion(s);
        pmShiftPlanGroupVO.setBdClassGroupVO(bdClassGroupService.queryBdClassGroupById(pmShiftPlanGroupVO.getClassGroupIdFk()));

        return pmShiftPlanGroupVO;
    }

    @Override
    public List<PmShiftPlanGroupVO> objectConversion(List<PmShiftPlanGroup> sList) {
        if (!CollectionUtil.isNotEmpty(sList)) {
            return null;
        } else {
            List<PmShiftPlanGroupVO> tList = new ArrayList();
            Iterator var3 = sList.iterator();

            while(var3.hasNext()) {
                PmShiftPlanGroup s = (PmShiftPlanGroup)var3.next();
                PmShiftPlanGroupVO t = this.objectConversion(s);
                Optional.ofNullable(t).ifPresent(tList::add);
            }

            return tList;
        }
    }


    /**
     * 校验
     *
     * @param pmShiftPlanGroupBindDTO 点转移计划组绑定dto
     */
    private void judgeRationality(PmShiftPlanGroupBindDTO pmShiftPlanGroupBindDTO){
        List<PmShiftPlanGroup> pmShiftPlanGroups = pmShiftPlanGroupMapper.selectList(new QueryWrapper<PmShiftPlanGroup>()
                .eq("SHIFT_PLAN_ID_FK", pmShiftPlanGroupBindDTO.getShiftPlanIdFk())
                .ne("SHIFT_MANAGE_ID_FK", pmShiftPlanGroupBindDTO.getShiftManageIdFk()));
        if(CollectionUtil.isEmpty(pmShiftPlanGroups) || CollectionUtil.isEmpty(pmShiftPlanGroupBindDTO.getClassGroupIdFks())){
            return;
        }
        List<Long> classGroupIds = pmShiftPlanGroups.stream().map(PmShiftPlanGroup::getClassGroupIdFk).collect(Collectors.toList());
        Assert.isTrue(Collections.disjoint(classGroupIds, pmShiftPlanGroupBindDTO.getClassGroupIdFks()),ResponseEnum.PM_SHIFT_PLAN_GROUP_INSERT_ERROR.getMessage());
    }
}
